import axios from 'axios';
import { cookieGet, delCookie,cookieSet } from "../storageCookie";

// 创建axios实例
const service = axios.create({
  baseURL: '/api',
});

// 请求拦截器
service.interceptors.request.use(
  config => {
    const Authorization = cookieGet('tsgfAuthorization');
    if (Authorization) {
      config.headers['Authorization'] = Authorization;
    }
    const auth = cookieGet('auth');
    if (auth) {
      config.params = { ...config.params, auth: auth };
    }
    return config;
  },
  error => {
    return Promise.reject(error);
  }
);

// 响应拦截器
service.interceptors.response.use(
  response => {
    // 处理业务层面的未授权
    if (response.data && response.data.code === 401) {
      return handleUnauthorized();
    }
    return response.data;
  },
  error => {
    // 处理HTTP层面的未授权
    if (error.response && error.response.status === 401) {
      return handleUnauthorized();
    }
    return Promise.reject(error);
  }
);



export default service;
async function handleUnauthorized() {
  delCookie('tsgfAuthorization');
  try {
    const res = await login();
    console.log(11111,);
    if (res.code === 200) {
      cookieSet("tsgfAuthorization", res.data.token);
        window.location.reload();
    }
  } catch (error) {
    console.error('自动登录失败', error);
    window.location.href = '/home';
  }
}



export const login = () => {
  return service({
    url: "/frontend/user/login",
    method: "post"
  });
};